<template>
    <div class="edit_dialog">
      <el-dialog :append-to-body="true" :visible.sync="show" @close="clear" width="800px" top="48px" center
                 :close-on-click-modal="false" :close-on-press-escape	='false'>
        <div slot="title" class="dialog-title">
          <p style="text-align:center;margin:0">{{title}}</p>
        </div>
        <div class="dialog_content">
          <el-form ref="form" :model="form"  labelPosition='left' label-width="85px" :size="size">
            <el-row :gutter="20">
            <el-col :span="12"><div class="grid-content">
              <el-form-item label="订单号">
                <el-input v-model="form.orderNo" style="width:270px" :size="size" placeholder="如果未填写，将会在保存订单时自动生成"></el-input>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item  prop="orderName">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  订单名称
                </span>
                <el-input v-model="form.orderName" style="width:270px" :size="size"></el-input>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item prop="orderStatus">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  订单状态
                </span>
                <el-select v-model="form.orderStatus" placeholder="请选择" style="width:270px">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.id"
                    :label="item.dictKey"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item prop="custId">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  客户
                </span>
                <checkCust @setCust="setCust" :defaultId="form.custId" @reomveCust="reomveCust" :disabled="title == '编辑订单'"></checkCust>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item prop="linkerId">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  联系人
                </span>
                <el-select v-model="linkerId" placeholder="请选择" style="width:270px" multiple :disabled="form.custId == ''">
                  <el-option
                    v-for="item in linkerOptions"
                    :key="item.id"
                    :label="item.linker"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item prop="currency">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  币种
                </span>
                <el-select v-model="form.currency" placeholder="请选择" :disabled="title == '编辑订单'" style="width:270px">
                  <el-option
                    v-for="item in currencyOptions"
                    :key="item.id"
                    :label="item.currencyName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item label="汇率" label-suffix="">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  汇率
                  <el-tooltip class="item" effect="dark" content="要先选择币种，再根据后台设置的执行汇率进行计算，暂不支持手动变更">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <span>{{form.currencyRate}}</span>
              </el-form-item>
            </div></el-col>
            <el-col :span="12"><div class="grid-content">
              <el-form-item label="结单日期">
                <el-date-picker
                  style="width: 270px"
                  type="datetime"
                  v-model="form.statementDate"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </div></el-col>
            <el-col :span="24"><div class="grid-content">
              <el-form-item prop="belongUserDtos">
                <span slot="label">
                  <span class="icon-bitian star_icon"></span>
                  业绩归属人
                </span>
                <div style="display: inline-block; position: relative">
                  <div v-for="(item,index) in form.belongUserDtos" :key="index" class="belong_item">
<!--                ? item.occupantUrl : userInfo.avatar    -->
                    <img :src="item.occupantUrl ? item.occupantUrl : defaultUrl" class="occupant_img"/>

                    <el-select v-model="item.occupantId" placeholder="请选择">
                      <el-option
                        v-for="item in custOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <span style="width:95px;display: inline-block;margin-left: 28px">业绩占比</span>
                    <el-input v-model="item.occupantPercent" style="width: 60px;margin-right: 10px" @keyup.native="NumberReplace(index)"></el-input>%
                    <span class="icon-delete_icon" style="color: #2A97F9; cursor:pointer;" @click="deleteBelong(index)"></span>
                  </div>
                  <div>
                    <span class="icon-tianjiahuoxinjian" style="color: #2A97F9" @click="addBelong" :class="form.belongUserDtos != undefined && form.belongUserDtos.length > 0 ? 'add_btn' : ''"></span>
                  </div>
                </div>

              </el-form-item>
            </div></el-col>
            </el-row>
            <el-form-item label="备注" class="not_icon_label">
              <el-input v-model="form.remarks" type="textarea" rows="5"></el-input>
            </el-form-item>




          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit('form')" size="small" :loading="loading">保 存</el-button>
          <el-button @click="clear" size="small">取 消</el-button>
        </div>
      </el-dialog>

<!-- 选择客户 -->

    </div>
</template>

<script>
  import {enterpriseUser} from '@/api/customer'
  import {queryOrderStatus, queryLinker, queryUser, saveOrder, orderDetail, editOrder, getUser} from '@/api/order'
  import {getRateList} from '@/api/system/rate'
  import {dataToString} from '@/util/util'
  import checkCust from './checkCust'
  import {mapState, mapGetters} from 'vuex'
    export default {
        name: "editOrder",
        props:['visible', 'title', 'order'],
        components: {
            checkCust
        },
        data() {
            return{
                defaultUrl:'http://zhilubt.oss-cn-hangzhou.aliyuncs.com/ERPSAAS/%E6%B5%99%E6%B1%9F%E7%9B%B4%E8%B7%AF%E7%BD%91%E7%BB%9C%E7%A7%91%E6%8A%80/product/imges/2019/11/11/big/96641/%E7%94%A8%E6%88%B7%E9%BB%98%E8%AE%A4%E5%9B%BE%E5%83%8F.png?Expires=1888823757&OSSAccessKeyId=LTAIW5fr3DK5Ij9f&Signature=uit9CzWxyoMXQPIC4byx7QE2VrI%3D&type=1',
                form: {
                    orderNo: '', // 订单号
                    orderName: '', // 订单名称
                    orderStatus: '', // 订单状态
                    custId: '', // 客户id
                    currency: '', // 币种
                    currencyRate: '', // 汇率
                    statementDate: '', // 订单日期
                    belongUserDtos:[{
                        occupantUrl: '',
                        occupantId: '',
                        occupantName: '',
                        occupantPercent: ''
                    }], // 业绩归属人信息
                    remarks: '' // 备注
                },
                show:false,
                linkerId: [], // 选中联系人
                statusOptions: [], // 订单状态数组
                currencyOptions: [], // 币种集合数组
                linkerOptions: [], // 联系人集合数组
                linkerNames: [], // 联系人名称集合
                custOptions: [], // 归属人集合数组
                custName: '', // 客户名称
                size: 'small',
                loading:false
            }
        },
        computed:{
          ...mapState(['common']),
          ...mapGetters([
              "userInfo",
          ]),
            currency() {
              return this.form.currency
            },
            belongUserDtos() {
              return this.form.belongUserDtos
            }
        },
        mounted() {
            getRateList().then(res => {
                this.currencyOptions = res.data.data
            })

            enterpriseUser().then(res => {
                this.custOptions = res.data.data
            })
            queryOrderStatus().then(res => {
                this.statusOptions = res.data.data
            })
            queryUser().then(res => {
                this.form.belongUserDtos[0].occupantId = res.data.data.id
                this.form.belongUserDtos[0].occupantName = res.data.data.name
                this.form.belongUserDtos[0].occupantPercent = 100
            })

            if(this.order) {
                orderDetail(this.order).then(res => {
                    this.form = res.data.data
                    if (this.form.custId) {
                        queryLinker(this.form.custId).then(res => {
                            this.linkerOptions = dataToString(res.data.data)
                            this.linkerId = this.form.linkerIds.split(',')
                        })
                    }

                })
            }
            this.show = this.visible

        },
        methods: {
            clear() {
                this.$emit('closeOrder', false)
            },
            NumberReplace(index) {
                var str = this.form.belongUserDtos[index]['occupantPercent']
                var len1 = str.substr(0, 1);
                var len2 = str.substr(1, 1);
                //如果第一位是0，第二位不是点，就用数字把点替换掉
                if (str.length > 1 && len1 == 0 && len2 != ".") {
                    str = str.substr(1, 1);
                }
                //第一位不能是.
                if (len1 == ".") {
                    str = "";
                }
                //限制只能输入一个小数点
                if (str.indexOf(".") != -1) {
                    var str_ = str.substr(str.indexOf(".") + 1);
                    if (str_.indexOf(".") != -1) {
                        str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
                    }
                }
                //正则替换，保留数字和小数点
                str = str.replace(/[^\d^\.]+/g,'')
                // //如果需要保留小数点后两位，则用下面公式
                // str = str.replace(/\.\d\d$/,'')
                this.form.belongUserDtos[index]['occupantPercent'] = str
            },
            submit() { // 提交订单
                let arr = []
                if (this.form.orderName == '') {
                    arr.push('订单名称')
                }
                if (this.form.orderStatus == '') {
                    arr.push('订单状态')
                }
                if (this.form.custId == '') {
                    arr.push('客户')
                }
                if (this.linkerId.length == 0) {
                    arr.push('联系人')
                }
                if (this.form.currency == '') {
                    arr.push('币种')
                }
                if (this.form.currencyRate == '') {
                    arr.push('汇率')
                }
                if (this.form.belongUserDtos.length == 0) {
                    arr.push('业绩归属人')
                }

                if (arr.length > 0) {
                    var str = arr.join(',')
                    this.$message({
                        type:'error',
                        message: `请填写${str}`
                    })
                    return
                } else {
                    let num = 0
                    this.form.belongUserDtos.forEach(value => {
                        num += Number(value.occupantPercent)
                    })
                    if(num != 100) {
                        this.$message({
                            type:'error',
                            message: '订单归属人业绩占比之和不等于100%'
                        })
                        return
                    } else {
                        this.form.linkerIds = this.linkerId.join(',')
                        this.form.linkerNames = this.linkerNames.join(',')
                        this.loading = true
                        if (this.title == '新建订单') {
                            saveOrder(this.form).then(res => {
                                if(res.data.success) {
                                    this.$emit('closeOrder', true)
                                    this.form = {}
                                    this.$message({
                                        type:'success',
                                        message:res.data.msg
                                    })
                                    this.loading = false
                                }
                            }).catch(() => {
                                this.loading = false
                            })
                        } else {
                            editOrder(this.form).then(res => {
                                if(res.data.success) {
                                    this.$emit('closeOrder', true)
                                    this.form = {}
                                    this.$message({
                                        type:'success',
                                        message:res.data.msg
                                    })
                                    this.loading = false
                                }
                            }).catch(() => {
                                this.loading = false
                            })
                        }
                    }
                }
            },
            setCust(id) { // 选择客户
                if (id) {
                    this.form.custId = id
                    queryLinker(id).then(res => {
                        this.linkerId = []
                        this.linkerOptions = res.data.data
                    })
                }
            },
            reomveCust() {
                this.form.custId = ''
                this.linkerId = []
            },
            addBelong() { // 添加业绩归属人
                var obj = {
                    "occupantUrl": this.defaultUrl,
                    "occupantId":"",
                    "occupantName":"",
                    "occupantPercent":"0"
                }
                this.form.belongUserDtos.push(obj)
            },
            deleteBelong(index) {
                this.belongUserDtos.splice(index, 1)
            }
        },
        watch: {
            currency(value) {
                this.currencyOptions.forEach((key) => {
                    if(key.id == value) {
                        this.form.currencyRate = key.rateValue
                    }
                })
            },
            belongUserDtos:{
                handler: function (value) {
                    if (value) {
                        let num = 0
                        value.forEach(key => {
                            num += Number(key.occupantPercent)
                        })
                        if (num > 100) {
                            this.$message({
                                type:'error',
                                message: '订单归属人业绩占比之和大于100%'
                            })
                        }
                    value.forEach(item => {
                        if(item.occupantId != '') {
                            getUser(item.occupantId).then(res => {
                                this.$nextTick(() => {
                                    this.$set(item, 'occupantUrl', res.data.avatar)

                                })
                            })
                        }
                    })


                    value.forEach((item) => {
                        this.custOptions.forEach(value1 => {
                            if (item.occupantId == value1.id) {
                                item.occupantName = value1.name
                            }
                        })
                    })

                    }
                },
                deep:true
            },
            linkerId(value) {
                this.linkerNames = []
                value.forEach(key => {
                    this.linkerOptions.forEach(item => {
                        if (key == item.id){
                            this.linkerNames.push(item.linker)
                        }
                    })
                })
            }
        }
    }
</script>

<style scoped>
  .edit_dialog{
    font-size: 13px;
  }
  .dialog_content{
    padding-left: 10px;
  }
  .img_box{
    position: relative;
    width: 50px;
    height:50px;
  }
  .occupant_img{
    height: 50px;
    width: 50px;
    border-radius: 50%;
    margin-right: 15px;
  }
  .remove_icon{
    display: inline-block;
    cursor: pointer;
    position: absolute;
    right: -10px;
    top: -10px;
  }
  .add_belong{
    font-size: 50px !important;
    display: inline-block;
    margin-top: 7px;
    cursor: pointer;
  }
  .belong_item{
    display: flex;
    align-items: center;
    margin: 5px;
    width: 500px;
  }
  .add_btn{
    display: inline-block;
    position: absolute;
    bottom: 14px;
    right: -16px;
    cursor: pointer;
  }
  .star_icon{
    color: rgb(245, 108, 108);
    font-size: 14px !important;
    margin-left: -14px;
    margin-right: -5px;
  }
</style>
